//
//  MWUserSettingVC.m
//  CarCare
//
//  Created by meway on 14-7-28.
//  Copyright (c) 2014年 baozun. All rights reserved.
//

#import "UserInfoViewController.h"

#import "UserNameViewController.h"

#import "FillAliViewController.h"

#import "ResetTelViewController.h"

#import "BaseWebViewController.h"
#import "RefreshMgr.h"

#define CELLHEIGHT 45
#define SECTIONHEIGHT 20
#define TOP (224 * __MAIN_RATIO_320)

@interface UserInfoViewController ()
<UITableViewDelegate,UITableViewDataSource,UIActionSheetDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,copy) NSArray *dataArr;

@property (nonatomic, strong) UIImageView *iconImageV;
@property (nonatomic, strong) UIImageView *iconBGImageV;
@property (nonatomic, strong) UILabel *nameL;

@end

@implementation UserInfoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	
    self.title = LOCSTRING(@"set_user_info");

    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.top = -64;
    self.scrollView.bounces = NO;
    //ImageNamed(@"defaultIcon")
    self.iconBGImageV = [Factory imageViewWithFrame:CGRectMake(0, 0, __MAIN_WIDTH, TOP + 64) image:nil onView:self.scrollView];
    UIImageView * outIconBGImageV = [Factory imageViewWithFrame:CGRectMake(0, 0, __MAIN_WIDTH, TOP + 64) image:nil onView:self.scrollView];
    outIconBGImageV.backgroundColor = [Theme mainNavColor];
    
    self.iconImageV = [Factory imageViewWithFrame:CGRectMake(0, 0,  90 * __MAIN_RATIO_375 ,  90 * __MAIN_RATIO_375) image:ImageNamed(@"defaultIcon") onView:self.scrollView];
    self.iconImageV.center = CGPointMake(__MAIN_WIDTH / 2, TOP / 2 + 6 * __MAIN_RATIO_375);

    __weak __typeof(self) wself = self;
    [[UIButton buttonEmptyWithFrame:self.iconImageV.frame click:^{
        if (![Check isVisiter]) {
            UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:wself cancelButtonTitle:LOCSTRING(@"cancel") destructiveButtonTitle:nil otherButtonTitles:LOCSTRING(@"menu_camera"),LOCSTRING(@"menu_pic"), nil];
            [actionSheet showInView:wself.tableView];
        }
    }] setupOnView:self.scrollView];
    
    self.iconImageV.layer.cornerRadius = self.iconImageV.frame.size.width / 2;
    self.iconImageV.layer.masksToBounds = YES;
    self.iconImageV.layer.borderColor = [UIColor whiteColor].CGColor;
    self.iconImageV.layer.borderWidth = 2.5;
    
    self.nameL = [Factory labelWithFrame:CGRectMake(50, self.iconImageV.bottom + 10, __MAIN_WIDTH - 100, 25) font:FONT_DEFAULT_Light(14) text:@"" textColor:[UIColor whiteColor] onView:self.scrollView textAlignment:NSTextAlignmentCenter];
    
    _dataArr = @[@[@"用户名",LOCSTRING(@"tel_num"),LOCSTRING(@"ali")]];
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, TOP, __MAIN_WIDTH, CELLHEIGHT * 3 ) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [Theme mainColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.bounces = NO;
    _tableView.scrollEnabled = NO;
    [self.scrollView addSubview:_tableView];
    [self.scrollView setContentSize:CGSizeMake(__MAIN_WIDTH, _tableView.frame.origin.y + _tableView.frame.size.height)];
    [self resetUserInfo];

}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	[_tableView reloadData];
    [self resetUserInfo];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)resetUserInfo{
    
    self.nameL.text = ([USERINFO.showName isNotNil]?USERINFO.showName:@"用户名");
    
//    [self.iconBGImageV setImageWithURL:[NSURL URLWithString:USERINFO.showImageURL]];

    __weak __typeof(self) wself = self;
    [self.iconImageV setImageWithURLRequest:[ImageHelper requestURLWithURLStr:USERINFO.showImageURL] placeholderImage:ImageNamed(@"defaultIcon.png") success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
        wself.iconImageV.image = image;
    } failure:nil];

}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
#pragma mark - uiactionsheet

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
        {
            if (!SYSTEMHELPER.isOpenMedia) {
                TipsView *tips = [TipsView textTipsWithTitle:LOCSTRING(@"tips_media_no_open") lightTitles:@[LOCSTRING(@"tips_media_open_1"),LOCSTRING(@"tips_media_open_2")]];
                [tips addOKButton:LOCSTRING(@"ok") clickOK:^{
                    [AlertMgr dismiss:TYPE_VIEW_ALERT];
                }];
                [AlertMgr showView:tips];
            }else{
                UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                picker.delegate = self;
                picker.allowsEditing = YES;
                [self presentViewController:picker animated:YES completion:nil];
 
            }
        }
            break;
            
        case 1:
        {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.allowsEditing = YES;
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            picker.delegate = self;
            [self presentViewController:picker animated:YES completion:nil];
        }
            break;
            
        default:
            break;
    }
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *oldImage = info[UIImagePickerControllerEditedImage];
  
    CGFloat length = oldImage.size.width * 9 / 10;

    oldImage = [ImageHelper cutImage:oldImage rect:CGRectMake(0, 0, length, length)];
    
    __weak __typeof(self) wself = self;
    [[[NetUser setIcon:oldImage] requestWithLoad:RequestLoadShowLoading|RequestLoadShowErrorTips] requestSuccess:^(id JSON) {
        USERINFO.headImageURL = JSON[@"Head_URL"];
        [AlertMgr showShortSuccessTextTips:@[JSON[@"errMsg"]]];
        [wself resetUserInfo];
    }];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_dataArr[section] count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return  0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return CELLHEIGHT;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	static NSString *identifier = @"UserSettingCell";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
									  reuseIdentifier:identifier];
		
        UIImage * rightImage = ImageNamed(@"cell_right");
        UIImageView * rightImageV = [Factory imageViewWithCenter:CGPointMake(__MAIN_WIDTH - 25, CELLHEIGHT/2) image:rightImage onView:cell.contentView];
        rightImageV.tag = 38;
        rightImageV.hidden = YES;
        
        UILabel *label = [Factory labelWithFrame:CGRectMake(150, 0, tableView.width - 150 - rightImage.size.width - 18, CELLHEIGHT) font:FONT_TABLE_TIPS text:@"" textColor:[COLOR_HEXSTRING(@"#454545") colorWithAlphaComponent:0.6] onView:cell.contentView textAlignment:NSTextAlignmentRight];
		label.tag = 1008611;
        label.numberOfLines = 1;

    }
	
    UIImageView * rightImageV = (UIImageView *)[cell.contentView viewWithTag:38];
    
    if (indexPath.row != 2) {
        rightImageV.hidden = NO;
    }else
    {
        rightImageV.hidden = (([USERINFO.aliAccount isNotNil]) ? YES : NO);
    }
    
    [[[UIView viewWithFrame:CGRectMake(0, 0, __MAIN_WIDTH, 0.5)] resetBackgroundColor:[Theme lineColor]] setupOnView:cell.contentView];
    [[[UIView viewWithFrame:CGRectMake(0, CELLHEIGHT - 0.5, __MAIN_WIDTH, 0.5)] resetBackgroundColor:[Theme lineColor]] setupOnView:cell.contentView];
    
	cell.textLabel.text = _dataArr[indexPath.section][indexPath.row];
    cell.textLabel.textColor = [Theme wordColor];
    cell.textLabel.font = FONT_TABLE_TITLE;
	UILabel *label = (UILabel *)[cell.contentView viewWithTag:1008611];
	
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:
                label.text = [USERINFO.showName isNotNil] ? USERINFO.showName : LOCSTRING(@"name_set_now");
                break;
            case 1:
                label.text = USERINFO.isVisiter ? @"游客手机" : @"更改";
                break;
            case 2:
                if([USERINFO.aliAccount isNotNil])[label setFrame:CGRectMake(150, 0, tableView.width - 150 - (tableView.width - rightImageV.origin.x - rightImageV.frame.size.width), CELLHEIGHT)];
                label.text = USERINFO.isVisiter ? @"游客帐号" : ([USERINFO.aliAccount isNotNil] ? USERINFO.aliAccount : LOCSTRING(@"ali_set_now"));
                break;
            default:
                break;
        }
    }

    return cell;
}

-(BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:{
                return YES;
                break;
            }
            case 1:
            {
                return YES;
                break;
            }
            case 2:
                return (![USERINFO.aliAccount isNotNil]);
                break;
            default:
                break;
        }

    }
    return YES;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if ([Check isVisiter]) {
        return;
    }
    switch (indexPath.section) {
        case 0:
            switch (indexPath.row) {
                case 0:{
                    UserNameViewController *vc = [[UserNameViewController alloc] init];
                    [self presentViewController:[UINavigationController navigationControllerWithRootViewController:vc] animated:YES completion:nil];
                    break;
                }
                case 1:
                {
                    ResetTelViewController *vc = [[ResetTelViewController alloc] init];
                    [self presentViewController:[UINavigationController navigationControllerWithRootViewController:vc] animated:YES completion:nil];
                    break;
                }
                case 2:
                    if ([USERINFO.aliAccount isNotNil]) {
                        //                [self.navigationController pushViewController:[[[AliViewController alloc] init] setupReturnBarButtonReturnRoot:NO] animated:YES];
                    }else{
                        FillAliViewController *vc = [[FillAliViewController alloc] init];
                        [self presentViewController:[UINavigationController navigationControllerWithRootViewController:vc] animated:YES completion:nil];
                    }
                    break;
                default:
                    break;
            }
            break;

        default:
            break;
    }
}

@end
